package es.udc.emarketapp.emarket.model.usersFacade.actions;


import es.udc.emarketapp.emarket.model.user.dao.SQLUserDAO;
import es.udc.emarketapp.emarket.model.user.dao.SQLUserDAOFactory;
import es.udc.emarketapp.emarket.model.user.vo.UserVO;
import es.udc.emarketapp.emarket.model.usersFacade.exceptions.IncorrectPasswordException;
import es.udc.emarketapp.emarket.model.usersFacade.util.PasswordEncrypter;
import es.udc.emarketapp.emarket.util.exceptions.model.NifCifAlreadyExistsException;
import es.udc.emarketapp.emarket.util.exceptions.model.UserNameAlreadyExistsException;
import es.udc.fbellas.j2ee.util.exceptions.InstanceNotFoundException;
import java.sql.Connection;

import es.udc.fbellas.j2ee.util.exceptions.InternalErrorException;
import es.udc.fbellas.j2ee.util.exceptions.ModelException;
import es.udc.fbellas.j2ee.util.sql.TransactionalPlainAction;

public class ChangePasswordAction implements TransactionalPlainAction {

    private String idUser;
    private String oldClearPassword;
    private String newClearPassword;

    public ChangePasswordAction(String idUser, String oldClearPassword,
            String newClearPassword) {
        this.idUser = idUser;
        this.oldClearPassword = oldClearPassword;
        this.newClearPassword = newClearPassword;
    }

    public Object execute(Connection connection)
            throws InstanceNotFoundException, IncorrectPasswordException,
        InternalErrorException {

        SQLUserDAO userDAO = SQLUserDAOFactory.getDAO();
        UserVO userVO = userDAO.findById(connection, idUser);

        String storedPassword = userVO.getPass();

        if(!PasswordEncrypter.isClearPasswordCorrect(oldClearPassword, storedPassword)){
            throw new IncorrectPasswordException(idUser);
        }

        userVO.setPass(PasswordEncrypter.crypt(newClearPassword));

        userDAO.update(connection, userVO);

         return userVO;

    }
}
